<template>
    <n-card class="search-form">
        <SearchForm
            :items="searchFormItems"
            v-model:value="tableConfig.params!"
            @submit="onSearchSubmit"
        />
    </n-card>

    <n-card>
        <Tool @add="onEdit" />
        <TablePagination ref="tableRef" :config="tableConfig" />
    </n-card>

    <ModalForm
        :items="formItems"
        v-model:show="formShow"
        v-model:value="formState"
        :loading="submiting"
        @submit="onSubmit"
    />
</template>

<script setup lang="ts">
import { FormItemsConfig, ModalForm } from '@/components/form'
import SearchForm from '@/components/form/src/SearchForm.vue'
import {
    IAuthUser,
    IAuthUserEditParameter,
    IAuthUserListParameter
} from '@/types/auth/user'
import { reactive, ref, h, computed, nextTick } from 'vue'
import { stateOptions } from './options'
import { TablePagination, TablePaginationConfig } from '@/components/table'
import {
    authUserAdd,
    authUserDelete,
    authUserList,
    authUserUpdate
} from '@/apis/auth/user'
import { NSpace, NTag, DataTableInst, NAvatar, useMessage } from 'naive-ui'
import { DeleteButton, EditButton } from '@/components/button'
import useState from '@/hooks/useState'

const message = useMessage()

/**
 * 搜索
 */
const searchFormItems: FormItemsConfig<IAuthUserListParameter> = [
    {
        field: 'keyword',
        label: '关键字',
        component: 'Input',
        props: {
            placeholder: '用户名'
        }
    },
    {
        field: 'state',
        label: '状态',
        component: 'Select',
        props: {
            placeholder: '全部状态',
            options: stateOptions,
            defaultValue: null
        }
    },
    {
        field: 'create_time',
        label: '创建时间',
        component: 'DatePicker',
        props: {
            type: 'daterange'
        }
    }
]
function onSearchSubmit() {
    tableRef.value?.run()
}

/**
 * 表格
 */
const tableRef = ref<DataTableInst>()
const tableConfig = reactive<TablePaginationConfig<IAuthUser>>({
    service: authUserList,
    params: {},
    columns: [
        {
            title: 'ID',
            key: 'id'
        },
        {
            title: '头像',
            key: 'avatar',
            render(rowData) {
                return h(NAvatar, {
                    round: true,
                    size: 'medium',
                    src: rowData.avatar
                })
            }
        },
        {
            title: '用户名',
            key: 'username'
        },
        {
            title: '创建时间',
            key: 'create_time'
        },
        {
            title: '状态',
            key: 'state',
            render(rowData) {
                const state = stateOptions.find(
                    (item) => item.value === rowData.state
                )
                return h(
                    NTag,
                    {
                        size: 'small',
                        type: state?.theme,
                        bordered: false
                    },
                    { default: () => state?.label }
                )
            }
        },
        {
            title: '操作',
            key: '_actions',
            width: 148,
            render(rowData) {
                return h(
                    NSpace,
                    {},
                    {
                        default: () => [
                            h(DeleteButton, {
                                service: () =>
                                    authUserDelete({ id: rowData.id }),
                                onDone: () => tableRef.value?.run(),
                                buttonProps: {
                                    // @ts-ignore
                                    disabled: rowData._protect
                                }
                            }),
                            h(EditButton, {
                                onClick: () => onEdit(rowData)
                            })
                        ]
                    }
                )
            }
        }
    ]
})

/**
 * 编辑
 */
const formItems = computed<FormItemsConfig<IAuthUserEditParameter>>(() => {
    return [
        {
            field: 'username',
            label: '用户名',
            component: 'Input',
            props: {
                placeholder: '请输入用户名'
            },
            rule: { required: true, min: 2, max: 20 }
        },
        {
            field: 'password',
            label: '密码',
            component: 'Input',
            props: {
                placeholder: formState.value?.id
                    ? '不输入则不修改'
                    : '请输入密码'
            },
            rule: {
                required: formState.value?.id ? false : true,
                min: 6,
                max: 20
            }
        },
        {
            field: 'avatar',
            label: '头像',
            component: 'UploadImage',
            props: {
                single: true
            },
            rule: { required: true }
        },
        {
            field: 'state',
            label: '状态',
            component: 'RadioGroup',
            props: {
                options: stateOptions,
                'default-value': 1
            }
        }
    ]
})
const defaultState: IAuthUserEditParameter = {
    username: '',
    password: '',
    avatar: '',
    state: 1
}
const formState = ref<IAuthUserEditParameter>({ ...defaultState })
const formShow = ref(false)
function onEdit(rowData?: IAuthUser) {
    formShow.value = true
    nextTick(() => {
        if (rowData) {
            formState.value = { ...rowData }
        } else {
            formState.value = { ...defaultState }
        }
    })
}

const { state: submiting, setState: setSubmiting } = useState()
function onSubmit() {
    setSubmiting(true)
    const API = formState.value.id ? authUserUpdate : authUserAdd
    API(formState.value)
        .then(() => {
            formShow.value = false
            tableRef.value?.run()
            message.success('操作成功')
        })
        .catch((e: Error) => {
            message.error(e.message)
        })
        .finally(() => setSubmiting(false))
}
</script>
